package mo.tags.greedy;

public class L581 {

    public int findUnsortedSubarray(int[] nums) {
        int max = Integer.MIN_VALUE, right = -1;
        int min = Integer.MAX_VALUE, left = -1;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (nums[i] >= max) {
                max = nums[i];
            } else {
                right = i;
            }
            if (nums[n-1-i] <= min) {
                min = nums[n-1-i];
            } else {
                left = n - 1 - i;
            }
        }
        return right == -1 ? 0 : right - left + 1;
    }

}
